#!/usr/bin/env python
# -*- coding: UTF-8 -*-

__author__ = "Patryk Szymczak"
__version__ = "0.4"

import sys, os
import signal

from plugin_factory import PluginFactory
from loggers import loggers
from dbus_parser import _Parser, process_introspection_data, DBusObject

def daemonize(option, opt, value, parser):
    print 'daemonizing...'
    
    stdin='/dev/null'
    stdout='/dev/null'
    stderr='/dev/null'
    #stdout='/tmp/daemon.log'
    #stderr='/tmp/daemon.log'
    
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)   # Exit first parent.
    except OSError, e:
        sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
        sys.exit(1)
 
    # Decouple from parent environment.
    #os.chdir("/")
    os.umask(0)
    os.setsid()
 
    # Do second fork.
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)   # Exit second parent.
    except OSError, e:
        sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
        sys.exit(1)
 
    # Now I am a daemon!
 
    # Redirect standard file descriptors.
    si = open(stdin, 'r')
    so = open(stdout, 'a+')
    se = open(stderr, 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())



if __name__ == "__main__":    
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("-d", "--daemonize", action="callback", callback=daemonize,
                      help="daemonize application")
    parser.add_option("-v", "--verbose", dest="verbose", default=None,
                      help="verbose level (CRITICAL, ERROR, WARNING, INFO, DEBUG)")
    parser.add_option("-s", "--screen", action="store_true", dest="screen", default=None,
                      help="debug to screen, additional stdout debug")

    (options, args) = parser.parse_args()
    logger = loggers('sms-middleware', 'sms-middleware.log', options.verbose, options.screen)
    
    dbus_object = DBusObject(logger)
    dbus_object.initialize()
    dbus_object.build_ifaces()
    
    p_factory = PluginFactory(logger)
    p_factory.scan_for_plugins()
    dbus_object.p_factory = p_factory
    
    # test
    """
    dbus_object.cbMessagebookReply([(1, 'unread', '+48695759817', 'ala ma kota', dbus_object.interfaces),
                                    (2, 'unread', '+48695759817', 'call +48695759817', dbus_object.interfaces),
                                    (3, 'unread', '+48695759817', 'RPC ', dbus_object.interfaces),
                                    (4, 'unread', '+48695759817', 'rpc ls', dbus_object.interfaces),
                                    (5, 'unread', '+48695759817', 'rpc pwd', dbus_object.interfaces),
                                    (6, 'unread', '+48503198538', 'dupa', dbus_object.interfaces),
                                    (6, 'unread', '+47797987967', 'dupa', dbus_object.interfaces),
                                    ])
    """
    try:
        logger.info('sms-middleware server running...')
        dbus_object.run()
    
    except KeyboardInterrupt:
        dbus_object.quit()
        
    else:
        logger.info("Normal exit")
        sys.exit(0)
    
